package com.cjj.nacos.config;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Configuration
public class NacosConfig implements ApplicationRunner {

    @Autowired(required = false)
    private NacosAutoServiceRegistration registration;

    @Value("${server.port}")
    private Integer port;

    @Bean
    @Primary
    @Qualifier("nacosRestTemplate")
    @LoadBalanced
    public RestTemplate restTemplate() {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectionPool(new ConnectionPool(200, 60, TimeUnit.SECONDS))
                .build();
        OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory(okHttpClient);
        return new RestTemplate(requestFactory);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (registration != null && port != null) {
            registration.setPort(port);
            registration.start();
        }
    }

}
